﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace B.S.BaseData.ReadAPI.Controllers
{
	/// <summary>
	/// 文件上传
	/// </summary>
	[Route("api/[controller]/[action]")]
	[ApiController]
	public class UpLoadFileController : ControllerBase
	{
		IConfiguration configuration;
		IWebHostEnvironment  webHostEnvironment;

		public UpLoadFileController(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
		{
			this.configuration = configuration;
			this.webHostEnvironment = webHostEnvironment;
		}


		/// <summary>
		/// 上传图片
		/// </summary>
		/// <param name="formFile"></param>
		/// <returns></returns>
		[HttpPost]
		public async Task<IActionResult> UploadFiles(IFormFile formFile)
		{
			try
			{
				// 检查文件是否为空
				if (formFile == null || formFile.Length == 0)
				{
					return BadRequest("请选择有效的文件");
				}

				// 检查文件大小（转换为MB）
				var fileSize = formFile.Length / 1024 / 1024;
				var sizeLimit = Convert.ToInt64(configuration["UpLoadFile:Limit"]);

				if (fileSize > sizeLimit)
				{
					return BadRequest($"文件大小超出限制，最大允许 {sizeLimit}MB");
				}

				// 获取文件后缀名
				var fileExt = Path.GetExtension(formFile.FileName).ToLower();
				// 将文件后缀放入string数组中
				var allowedExtensions = configuration["UpLoadFile:AllowExt"].Split(',');
				// 判断文件后缀是否在允许的范围内(后缀数组中包含该后缀)
				if (!allowedExtensions.Contains(fileExt))
				{
					return BadRequest($"文件格式不正确，只允许 {string.Join(", ", allowedExtensions)} 格式");
				}

				// 生成文件名
				var newFileName = $"{DateTime.Now:yyyyMMddHHmmssfff}-{Random.Shared.Next(10000, 99999)}{fileExt}";

				// 创建文件夹路径
				var folderPath = Path.Combine(
					webHostEnvironment.WebRootPath,
					"UpLoadFile",
					"Images",
					DateTime.Now.ToString("yyyyMMdd"));

				// 确保目录存在
				Directory.CreateDirectory(folderPath);

				// 完整文件路径
				var filePath = Path.Combine(folderPath, newFileName);

				// 保存文件
				using (var fs = new FileStream(filePath, FileMode.Create))
				{
					await formFile.CopyToAsync(fs);
				}

				// 构造访问URL
				var baseUrl = $"{Request.Scheme}://{Request.Host}";
				var fileUrl = $"{baseUrl}/UploadFiles/Images/{DateTime.Now:yyyyMMdd}/{newFileName}";

				return Ok(new
				{
					success = true,
					message = "文件上传成功",
					url = fileUrl,
					fileName = newFileName,
					fileSize = $"{formFile.Length / 1024} KB"
				});
			}
			catch (Exception ex)
			{
				return StatusCode(500, new
				{
					success = false,
					message = $"文件上传失败: {ex.Message}"
				});
			}
		}





	}
}
